{% extends 'base.html' %}
{% load patrowl_tags %}
{% block content %}

<style>
ul.ui-autocomplete {
  position: fixed;
  top: initial;
}
.table-sum>tbody>tr>td, .table-sum>thead>tr>th { padding: 1px; }
.table-sum>tbody>tr>td.ct{ text-align: center; }

.row.finding-stats > div {
  margin: 0;
  padding: 2px;
}

div.risk-grade { font-size: xx-large; padding: 10px; border-radius: 5px; }
div.risk-grade-A { background-color: limegreen; }
div.risk-grade-B { background-color: yellowgreen; }
div.risk-grade-C { background-color: orange; }
div.risk-grade-D { background-color: darkorange; }
div.risk-grade-E { background-color: orangered; }
div.risk-grade-F { background-color: red; }

span.badge-risk-grade-A { background-color: limegreen; }
span.badge-risk-grade-B { background-color: yellowgreen; }
span.badge-risk-grade-C { background-color: orange; }
span.badge-risk-grade-D { background-color: darkorange; }
span.badge-risk-grade-E { background-color: orangered; }
span.badge-risk-grade-F { background-color: red; }
span.badge-risk-grade-- { background-color: lightgray; }

div.tile {
  border-width: thin;
  border-style: solid;
  border-left-width: 1rem;
  border-radius: 3px;
  padding-bottom: 15px;
  text-align: center;
}
div.tile div { font-size: large; }
div.tile-critical { border-color: #cc0500; }
div.tile-high { border-color: #df3d03; }
div.tile-medium { border-color: #f9a009; }
div.tile-low { border-color: #ffcb0d; }
div.tile-info { border-color: #3498db; }

div.risk-trends {
  border-top-color: lightgray;
  border-top-style: solid;
}

.row {
    margin-left: -15px;
    margin-right: 15px;
}

</style>

<ul class="breadcrumb">
  <li><a href="{% url 'list_assets_view' %}">assets</a></li>
  <li><a href="/assets/details/{{ asset.id }}">{{ asset.value }}</a></li>
  <li class="active">details [<a href='/assets/edit/{{ asset.id }}'>edit</a>]</li>
</ul>

<div class="container-fluid" asset-id="{{asset.id}}">
  <div class="row">
    <div class="col-md-4">
      <dl class="dl-horizontal">
        <dt>Name</dt>
        <dd><b>{{ asset.name }}</b> ({{asset.type}})</dd>

        <dt>Value</dt>
        <dd>{{ asset.value }}</dd>

        <dt>Description</dt>
        <dd>{{ asset.description }}</dd>

        <dt>Tags</dt>
        <dd>
          {% for tag in asset.categories.all %}
          <span class="label label-primary">{{tag.value|lower}} <i class="glyphicon glyphicon-remove text-warning delete-tag-btn" tag-id="{{tag.id}}"></i></span>
          {% endfor %}
          <a href="#modal-edit-asset-tags" data-toggle="modal" data-target="#modal-edit-asset-tags">+ add</a>
        </dd>

        <dt>Criticity</dt>
        {% if asset.criticity == 'low' %}
        <dd><span class="label label-low">low</span></dd>
        {% elif asset.criticity == 'medium' %}
        <dd><span class="label label-medium">medium</span></dd>
        {% elif asset.criticity == 'high' %}
        <dd><span class="label label-critical">high</span></dd>
        {% endif %}

        <dt>Created at</dt>
        <dd>{{ asset.created_at|smartdate }}</dd>

        <dt>Download report</dt>
        <dd>
          <a href="/assets/api/v1/report/json/{{ asset.id }}">json</a> -
          <a href="/assets/api/v1/report/html/{{ asset.id }}">html</a> - pdf - raw
        </dd>
      </dl>
    </div><!-- End of first col -->

    <div class="col-md-6 tiles"> <!-- Second col -->
      <div class="row">
        <b>Findings Stats </b><span class="glyphicon glyphicon-stats"></span>
      </div>
      <div class="row finding-stats">
        <div class="col-md-2">
          <div class="tile tile-critical">
              <div>Critical:</div><span class="label label-critical">{{findings_stats.critical}}</span>
          </div>
        </div>
        <div class="col-md-2">
          <div class="tile tile-high">
      		    <div>High:</div><span class="label label-high">{{findings_stats.high}}</span>
          </div>
      	</div>
        <div class="col-md-2">
          <div class="tile tile-medium">
      		    <div>Medium:</div><span class="label label-medium">{{findings_stats.medium}}</span>
          </div>
      	</div>
        <div class="col-md-2">
          <div class="tile tile-low">
      		    <div>Low:</div><span class="label label-low">{{findings_stats.low}}</span>
          </div>
      	</div>
        <div class="col-md-2">
          <div class="tile tile-info">
      		    <div>Info:</div><span class="label label-info">{{findings_stats.info}}</span>
          </div>
      	</div>
      </div>
      <div class="row">
        <div class="col-md-12">
      		<b># Findings</b>: <i>{{findings_stats.total}} ({{findings_stats.new}} news, {{findings_stats.ack}} ackd.)</i><br/>
      		<b># Findings with CVSS > 7.0</b>: {% if findings_stats.cvss_gte_7 > 0 %} <i class="text-danger">{{findings_stats.cvss_gte_7}}{% else %} <i>0{% endif %}</i><br/>
      		<b># Scans related</b>: <i>{{scans_stats.performed}} performed, {{scans_stats.defined}} defined, {{scans_stats.running}} currently running</i><br/>
      		<b># Scans from engines</b>: <i>
          {% for engine, counter in engines_stats.items %}
            {{ engine }}: {{ counter }}{% if not forloop.last %}, {% endif %}
          {% endfor %}</i><br/>
      	</div>
      </div>
    </div>

    <div class="col-md-2 text-center"> <!-- Thrird col -->
      <div class="row">
      <b>Global Security Rating </b><span class="glyphicon glyphicon-dashboard"></span>
        <div class="risk-grade risk-grade-{{asset_risk_grade|keyvalue:'now'}}">
          <b>{{asset_risk_grade|keyvalue:"now"}}</b></div>
        </div><br/>
      <div class="row risk-trends">
      <span data-toggle="modal" data-target="#modal-asset-trends"><b>Trends </b><span class="glyphicon glyphicon-time"></span></span>
      </div>
      <div class="row">
        <div class="col-md-4" title="1 day ago">-1d
          {% if asset_risk_grade|keyvalue:"now" > asset_risk_grade|keyvalue:"day_ago" %}
          <span class="glyphicon glyphicon-arrow-down text-danger"></span>
          {% elif asset_risk_grade|keyvalue:"now" == asset_risk_grade|keyvalue:"day_ago" %}
          <span class="glyphicon glyphicon-minus"></span>
          {% else %}
          <span class="glyphicon glyphicon-arrow-up text-success"></span>
          {% endif %}
        </div>
        <div class="col-md-4">-1w
          {% if asset_risk_grade|keyvalue:"now" > asset_risk_grade|keyvalue:"week_ago" %}
          <span class="glyphicon glyphicon-arrow-down text-danger"></span>
          {% elif asset_risk_grade|keyvalue:"now" == asset_risk_grade|keyvalue:"week_ago" %}
          <span class="glyphicon glyphicon-minus"></span>
          {% else %}
          <span class="glyphicon glyphicon-arrow-up text-success"></span>
          {% endif %}
        </div>
        <div class="col-md-4">-1m
          {% if asset_risk_grade|keyvalue:"now" > asset_risk_grade|keyvalue:"month_ago" %}
          <span class="glyphicon glyphicon-arrow-down text-danger"></span>
          {% elif asset_risk_grade|keyvalue:"now" == asset_risk_grade|keyvalue:"month_ago" %}
          <span class="glyphicon glyphicon-minus"></span>
          {% else %}
          <span class="glyphicon glyphicon-arrow-up text-success"></span>
          {% endif %}
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-12">
      <!-- <h4>Quick report</h4> -->
      <p>
        {% for scope, counter in asset_scopes %}
          <a href="/findings/list?_scope={{ counter.id }}&_asset_id={{ asset.id }}" style="text-decoration:none;">
          {% if counter.critical > 0 %}
          <span class="label label-critical">{{ scope }}: {{ counter.critical }}/{{ counter.total }}</span>
          {% elif counter.high > 0 %}
          <span class="label label-high">{{ scope }}: {{ counter.high }}/{{ counter.total }}</span>
          {% elif counter.medium > 0 %}
          <span class="label label-medium">{{ scope }}: {{ counter.medium }}/{{ counter.total }}</span>
          {% elif counter.low > 0 %}
          <span class="label label-low">{{ scope }}: {{ counter.low }}/{{ counter.total }}</span>
          {% else %}
          <span class="label label-default">{{ scope }}: {{ counter.total }}</span>
          {% endif %}
          </a>
        {% endfor %}
        <a href="#" data-toggle="modal" data-target="#modal-scopes-details">+ details</a>
      </p>
    </div>
  </div>
</div>


<div class="container-fluid">
  <ul class="nav nav-tabs" id="menu_tabs_ul">
    <li class="active menu_findings"><a data-toggle="tab"  href="#findings_div">Findings ({{findings_stats.total}})</a></li>
    <li class="menu_remediations"><a data-toggle="tab" href="#remediations_div">Remediations</a></li>
    <li class="menu_scans"><a data-toggle="tab" href="#scans_div">Scans ({{scans_stats.defined}}|{{scans_stats.performed}})</a></li>
    <li class="menu_investigations"><a data-toggle="tab" href="#investigation_div">Investigate</a></li>
    <li class="menu_relation"><a data-toggle="tab" href="#relations_div">Relations/Artifacts</a></li>
    <li class="menu_owners"><a data-toggle="tab" href="#owners_div">Owners</a></li>
    <li class="menu_alerts"><a data-toggle="tab" href="#alerts_div">Alerts</a></li>
    <li class="menu_comments"><a data-toggle="tab" href="#comments_div">Comments</a></li>
  </ul>
  <div class="tab-content">
    <div id="findings_div" class="tab-pane fade in active">
      <div class="dropdown">
        <button class="btn btn-primary btn-xs dropdown-toggle" type="button" id="dropdown-menu-actions" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
          Actions
          <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" aria-labelledby="dropdown-menu-actions">
          <li><a class="btn-ack" href="#">Ack selected findings</a></li>
          <li><a class="btn-compare-selected" href="#">Compare selected findings (2 findings max.)</a></li>
          <li><a class="btn-delete-selected" href="#">Delete selected findings (no confirm)</a></li>
        </ul>
      </div>
      <table class="table table-hover" id="table" data-toggle="table">
        <thead>
          <tr>
            <th><input type="checkbox" onClick="toggle(this)" /></th>
            <th>Title</th>
            <th>Type</th>
            <th>Severity</th>
            <th>Status</th>
            <th>From</th>
            <th>Last update</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {% for finding in findings %}
          <tr class='dblclickable-row' data-href='/findings/details/{{ finding.id }}'>
            <td><input type="checkbox" class="radio" name="finding" value="{{ finding.id }}"/></td>
            <td>{{ finding.title|truncatechars:105 }}</td>
            <td>{{ finding.type }}</td>
            <td>
              {% if finding.severity == 'critical' %}
              <span class="label label-critical">{{ finding.severity }}</span>
              {% elif finding.severity == 'high' %}
              <span class="label label-high">{{ finding.severity }}</span>
              {% elif finding.severity == 'medium' or finding.severity == 'moderate' %}
              <span class="label label-medium">{{ finding.severity }}</span>
              {% elif finding.severity == 'low' %}
              <span class="label label-low">{{ finding.severity }}</span>
              {% else %}
              <span class="label label-info">{{ finding.severity }}</span>
              {% endif %}
            </td>
            {% if finding.status == 'new' %}
            <td class="text-danger">{{ finding.status }}</td>
            {% else %}
            <td>{{ finding.status }}</td>
            {% endif %}
            <td>{{ finding.engine_type }}</td>
            <td>{{ finding.updated_at|smartdate }}</td>
            <td>
              <div class="btn-toolbar btn-group">
                <a href="/findings/details/{{ finding.id }}" class="btn btn-default btn-xs">
                  <span class="glyphicon glyphicon-plus-sign"></span></a>
                <a href="/findings/delete/{{ finding.id }}" class="btn btn-danger btn-xs"
                data-toggle="modal" data-target="#modal-delete-finding"
                finding-id="{{ finding.id }}" finding-title="{{ finding.title }}">
                <span class="glyphicon glyphicon-remove"></span></a>
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    <div id="remediations_div" class="tab-pane fade">
      <table class="table table-hover" id="table" data-toggle="table">
        <thead>
          <tr>
            <th>Severity</th>
            <th>Remediations</th>
            <th>Scopes</th>
            <th>Related findings</th>
            <th>Status</th>
            <th>Last update</th>
          </tr>
        </thead>
        <tbody>
          {% for finding in findings %}
          {% if finding.severity != "info" and finding.solution != "n/a" %}
          <tr>
            <td>
              {% if finding.severity == 'critical' %}
              <span class="label label-critical">{{ finding.severity }}</span>
              {% elif finding.severity == 'high' %}
              <span class="label label-high">{{ finding.severity }}</span>
              {% elif finding.severity == 'medium' or finding.severity == 'moderate' %}
              <span class="label label-medium">{{ finding.severity }}</span>
              {% elif finding.severity == 'low' %}
              <span class="label label-low">{{ finding.severity }}</span>
              {% else %}
              <span class="label label-default">{{ finding.severity }}</span>
              {% endif %}
            </td>
            <td>{{ finding.solution }}</td>
            <td>
              {% for scope in finding.scope_list %}
                {{scope}}{% if not forloop.last %},{% endif %}
              {% endfor %}
            </td>
            <td><a href="/findings/details/{{ finding.id }}">{{ finding.id }}</a></td>
            <td>{{ finding.status }}</td>
            <td>{{ finding.updated_at|smartdate }}</td>
          </tr>
          {% endif %}
          {% endfor %}
        </tbody>
      </table>
    </div>
    <div id="scans_div" class="tab-pane fade">
      <h5>Scan definitions [<a href="/scans/defs/add?asset_id={{asset.id}}">+ add new</a>]</h5>
      <table class="table table-hover" id="table" data-toggle="table">
        <thead>
          <tr>
            <th>Title</th>
            <th># Scans</th>
            <th>Type</th>
            <th>Engine</th>
            <th>Status</th>
            <th>Last update</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {% for scan_def in scan_defs %}
          <tr>
            <td><a href="/scans/defs/details/{{ scan_def.id }}" class="text-primary">{{ scan_def.title }}</a></td>
            <td>{{ scan_def.scan_set_count }}</td>
            <td>{{ scan_def.scan_type }}</td>
            <td>{{ scan_def.engine_type_name }}</td>
            {% if scan_def.scan_type == "periodic" %}
              {% if scan_def.enabled %}
              <td><span class="label label-success">Enabled</span></td>
              {% else %}
              <td><span class="label label-danger">Disabled</span></td>
              {% endif %}
            {% elif scan_def.scan_type == "single" %}
                <td><span class="label label-default">n/a</span></td>
            {% endif %}
            <td>{{ scan_def.updated_at|smartdate }}</td>
            <td>
              <button type="button" class="btn btn-default btn-xs" aria-haspopup="true" aria-expanded="false" onclick="location.href='/scans/defs/edit/{{ scan_def.id }}'">
                <span class="glyphicon glyphicon-edit"></span></button>
              {% if scan_def.scan_type == "periodic" %}
                {% if scan_def.enabled %}
                <button type="button" class="btn btn-warning btn-xs btn-change-status" aria-haspopup="true" aria-expanded="false" scan-id="{{ scan_def.id }}">
                  Disable</button>
                {% else %}
                <button type="button" class="btn btn-success btn-xs btn-change-status" aria-haspopup="true" aria-expanded="false" scan-id="{{ scan_def.id }}">
                  Enable</button>
                {% endif %}
              {% elif scan_def.scan_type == "single" %}
                <button type="button" class="btn btn-warning btn-xs btn-run-now" scan-id="{{ scan_def.id }}" scan-title="{{ scan_def.title }}" data-toggle="modal" data-target="#modal-run-scan">
                  Run </button>
              {% endif %}
              <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#modal-delete-scan-def"
                scan-id="{{ scan_def.id }}" scan-title="{{ scan_def.title }}">
                <span class="glyphicon glyphicon-remove"></button>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>

      <hr>

      <h5>Scans performed</h5>
      <table class="table table-hover" id="table" data-toggle="table">
        <thead>
          <tr>
            <th data-field="title">Title</th>
            <th data-field="status">Status</th>
            <th data-field="progress" style="width:20%">Progress</th>
            <th data-field="updated_at">Last update</th>
            <th data-field="actions">Actions</th>
          </tr>
        </thead>
        <tbody>
          {% for scan in scans %}
            <tr class='dblclickable-row' data-href='/scans/details/{{scan.id}}'>
              <td>[{{ scan.engine_type_name }}] {{ scan.title }}</td>
              {% if scan.status == "started" %}
              <td class="text-center"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate" style="color:orange" title="Started"></span></td>
              {% elif scan.status == "stopping"  %}
              <td class="text-center"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate" style="color:red" title="Stopping"></span></td>
              {% elif scan.status == "stopped"  %}
              <td class="text-center"><span class="glyphicon glyphicon-remove" style="color:red" title="Stopped"></span></td>
              {% elif scan.status == "finished"  %}
              <td class="text-center"><span class="glyphicon glyphicon-ok" style="color:green" title="Finished"></span></td>
              {% elif scan.status == "scheduled"  %}
              <td class="text-center"><span class="glyphicon glyphicon-time" style="color:blue" title="Scheduled"></span></td>
              {% elif scan.status == "enqueued"  %}
              <td class="text-center"><span class="glyphicon glyphicon-pushpin" style="color:orange" title="Enqueued"></span></td>
              {% elif scan.status == "error"  %}
              <td class="text-center"><span class="glyphicon glyphicon-fire" style="color:red" title="Error"></span></td>
              {% else %}
              <td>{{ scan.status }}</td>
              {% endif %}

              <!--  -->
              <td class="scan-progress" style="vertical-align: middle;">
                <div class="progress" id="pb-{{ scan.id }}" style="margin-bottom: 3px;">
                  {% if scan.status == "finished" %}
                  <div class="progress-bar progress-bar progress-bar-critical" role="progressbar" style="width:{{ scan.summary.critical | perc:scan.summary.total }}%">
                    {{ scan.summary.critical }}
                  </div>
                  <div class="progress-bar progress-bar progress-bar-high" role="progressbar" style="width:{{ scan.summary.high | perc:scan.summary.total }}%">
                    {{ scan.summary.high }}
                  </div>
                  <div class="progress-bar progress-bar progress-bar-medium" role="progressbar" style="width:{{ scan.summary.medium | perc:scan.summary.total }}%">
                    {{ scan.summary.medium }}
                  </div>
                  <div class="progress-bar progress-bar progress-bar-low" role="progressbar" style="width:{{ scan.summary.low | perc:scan.summary.total }}%">
                    {{ scan.summary.low }}
                  </div>
                  <div class="progress-bar progress-bar progress-bar-info" role="progressbar" style="width:{{ scan.summary.info | perc:scan.summary.total }}%">
                    {{ scan.summary.info }}
                  </div>
                  {% else %}
                  <div class="progress-bar progress-bar-striped active" role="progressbar">
                    -
                  </div>
                  {% endif %}
                </div>
              </td>
              <td>{{ scan.updated_at|smartdate }}</td>
              <td>
                <button type="button" class="btn btn-default btn-xs" title="Details" onclick="location.href='/scans/details/{{ scan.id }}'">
                  details</button>
                <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#modal-delete-scan"
                  scan-id="{{ scan.id }}" scan-title="{{ scan.title }}">
                  <span class="glyphicon glyphicon-remove"></button>
              </td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    <div id="investigation_div" class="tab-pane fade">
      <h4>Investigations links</h4>
      {% for link in investigation_links %}
      <div>
        <a href="{{ link|keyvalue:'link' }}" target="_blank">{{ link|keyvalue:"name" }}</a>
      </div>
      {% endfor %}
    </div>
    <div id="relations_div" class="tab-pane fade">
      <h4>Related asset groups</h4>
      {% if asset.assetgroup_set.all|length == 0 %}
      No asset groups.
      {% else %}
      <table class="table table-hover" data-toggle="table" data-sort-name="value" data-sort-order="desc">
        <thead>
          <tr>
            <th data-field="name">Name</th>
            <th data-field="assets">Assets</th>
            <th data-field="criticity">Criticity</th>
            <th data-field="score">Score</th>
            <th data-field="updated_at">Last update</th>
            <th data-field="actions">Actions</th>
          </tr>
        </thead>
        <tbody>
        {% for asset_group in asset.assetgroup_set.all %}
        <tr>
          <td><a href="/assets/groups/details/{{ asset_group.id }}">{{ asset_group.name }}</a></td>
          <td>{{ asset_group.get_asset_names|truncatechars:128 }}</td>
          {% if asset_group.criticity == 'low' %}
          <td><span class="label label-low">Low</span></td>
          {% elif asset_group.criticity == 'medium' %}
          <td><span class="label label-medium">Medium</span></td>
          {% elif asset_group.criticity == 'high' %}
          <td><span class="label label-critical">High</span></td>
          {% endif %}
          <td><span class="badge badge-risk-grade-{{ asset_group.get_risk_grade }}">{{ asset_group.get_risk_grade }}</span></td>
          <td>{{ asset_group.updated_at|smartdate }}</td>
          <td>
            <button type="button" class="btn btn-default btn-xs" aria-haspopup="true" aria-expanded="false" onclick="location.href='/assets/groups/details/{{ asset_group.id }}'">
              <span class="glyphicon glyphicon-eye-open"></span></button>
            <button type="button" class="btn btn-warning btn-xs" aria-haspopup="true" aria-expanded="false" onclick="location.href='/assets/groups/edit/{{ asset_group.id }}'">
              <span class="glyphicon glyphicon-pencil"></span></button>
            <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#modal-delete-asset-group"
              asset-group-id="{{ asset_group.id }}" asset-group-value="{{ asset_group.name }}">
              <span class="glyphicon glyphicon-remove"></span></button>
          </td>
        </tr>
      {% endfor %}
      </tbody>
      </table>
      {% endif %}
      <hr>
      <h4>External References</h4>
      <!-- Todo (CVE, advisories, ...). -->
      {% if references|length == 0 %}
        No external references found.
      {% else %}
        {% for ref in references %}
          {{ref}}: {{references|keyvalue:ref|join:", "}}
          <br/>
        {% endfor %}
      {% endif %}

    </div>
    <div id="owners_div" class="tab-pane fade">
      <h4>Owners [<a href="/assets/owners/add">+ add new</a>]</h4>
      {% for owner in asset.assetowner_set.all %}
      <dl class="dl-horizontal">
        <dt>Name</dt>
        <dd>{{ owner.name }} (<a href="{{ owner.url }}">link</a>)</dd>

        <dt>Comments</dt>
        <dd>{{ owner.comments|linebreaks }}</dd>

        <dt>Contacts list</dt>
        <dd>
          <ul>
          {% for contact in owner.contacts.all %}
            <li>{{ contact.name }} - {{ contact.phone }} - <a href="mailto:{{ contact.email }}">{{ contact.email }}</a></li>
          {% endfor %}
          </ul>
        </dd>

        <dt>Documents</dt>
        <dd>
          <a href="#" data-toggle="modal" data-target="#modalDocument">+ add document</a>
          <ul>
          {% for doc in owner.documents.all %}
            <li>
              {% if doc.tlp_color == 'red' %}
              <a href="/assets/owners/getdoc/{{doc.id}}">{{ doc.filename }}</a> - {{ doc.doctitle }} <span class="label label-danger">TLP:RED</span> ({{ doc.updated_at|date:"Y/m/d\-H:i:s" }})
              {% elif doc.tlp_color == 'amber' %}
              <a href="/assets/owners/getdoc/{{doc.id}}">{{ doc.filename }}</a> - {{ doc.doctitle }} <span class="label label-warning">TLP:AMBER</span> ({{ doc.updated_at|date:"Y/m/d\-H:i:s" }})
              {% elif doc.tlp_color == 'green' %}
              <a href="/assets/owners/getdoc/{{doc.id}}">{{ doc.filename }}</a> - {{ doc.doctitle }} <span class="label label-success">TLP:GREEN</span> ({{ doc.updated_at|date:"Y/m/d\-H:i:s" }})
              {% elif doc.tlp_color == 'white' %}
              <a href="/assets/owners/getdoc/{{doc.id}}">{{ doc.filename }}</a> - {{ doc.doctitle }} <span class="label label-white" style="color: black;">TLP:WHITE</span>({{ doc.updated_at|date:"Y/m/d\-H:i:s" }})
            {% endif %}
             </li>
          {% endfor %}
          </ul>
        </dd>
      </dl>
      {% endfor %}
    </div>
    <div id="alerts_div" class="tab-pane fade">
      <h4>Alerts</h4>
      @Todo: Related alert rules and notified alerts
    </div>
    <div id="comments_div" class="tab-pane fade">
      <h4>Comments</h4>
      @Todo: Comments
    </div>
  </div>
</div>

<div class="container">
  {% if messages %}
  <ul class="messages">
      {% for message in messages %}
      <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
      <!-- <div class="alert alert-dismissible alert-success fade in">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <p{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p>
      </div> -->
      {% endfor %}
  </ul>
  {% endif %}
</div>

<!-- Scope details modal -->
<div class="modal fade" id="modal-scopes-details" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header bg-primary">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Details</h4>
      </div>

      <!-- Modal Body -->
      <div class="modal-body">
        <div id="scopes-details">
          <!-- Content -->
          <table class="table table-sum table-hover">
            <thead>
              <tr>
                <th>Scopes</th>
                <th>Critical</th>
                <th>High</th>
                <th>Medium</th>
                <th>Low</th>
                <th>Info</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              {% for scope, counter in asset_scopes %}
              <tr>
                <td>{{scope}}</td>
                <td class="col-md-1 ct">
                  {% if counter.critical > 0 %}
                  <span class="label label-critical">{{counter.critical}}</span>
                  {% else %}
                  {{counter.critical}}
                  {% endif %}
                </td>
                <td class="col-md-1 ct">
                  {% if counter.high > 0 %}
                  <span class="label label-high">{{counter.high}}</span>
                  {% else %}
                  {{counter.high}}
                  {% endif %}
                </td>
                <td class="col-md-1 ct">
                  {% if counter.medium > 0 %}
                  <span class="label label-medium">{{counter.medium}}</span>
                  {% else %}
                  {{counter.medium}}
                  {% endif %}
                </td>
                <td class="col-md-1 ct">
                  {% if counter.low > 0 %}
                  <span class="label label-low">{{counter.low}}</span>
                  {% else %}
                  {{counter.low}}
                  {% endif %}
                </td>
                <td class="col-md-1 ct">{% if counter.info > 0 %}
                  <span class="label label-info">{{counter.info}}</span>
                  {% else %}
                  {{counter.info}}
                  {% endif %}
                </td>
                <td class="col-md-1 ct"><strong>{{counter.total}}</strong></td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
        <button type="button" class="btn btn-xs btn-primary col-sm-12" data-dismiss="modal">Cancel</button><br/>
      </div>
    </div>
  </div>
</div>

<!-- Delete findings modal -->
<div class="modal fade" id="modal-delete-finding" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header bg-primary">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Delete Finding</h4>
      </div>

      <!-- Modal Body -->
      <div class="modal-body">
        <div id="delete-finding">
          <!-- Content -->
        </div>
        Confirm Deleting?
        <button type="button" class="btn btn-xs btn-warning btn-delete-finding" data-dismiss="modal" autofocus>Yes</button>
        <button type="button" class="btn btn-xs btn-primary" data-dismiss="modal">No</button>
      </div>
    </div>
  </div>
</div>

<!-- Modal Edit tags -->
<div class="modal fade" id="modal-edit-asset-tags" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header bg-primary">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Add tags</h4>
      </div>

      <!-- Modal Body -->
      <div class="modal-body">
        <div id="asset-tags">
          <!-- Content -->
          <b>Current tags</b>: {{ asset.categories.all|join:", " }}<br/>
          <p class="text-warning">
            Warning: <br/>
            1/ All sub-tags will be deleted if a parent tag is added<br/>
            2/ Parent tag will be deleted if a child tag is added</p>

          <form class="search-asset-tags-form" action="/assets/api/v1/details/{{asset.id}}/add_tag" method="post">
            {% csrf_token %}
            <input type="text" id="input-search-tags" name="input-search-tags"/><button class="btn btn-xs btn-warning" type="submit">+</button>
          </form>

        </div>
      </div>

      <!-- Modal Footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-xs btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Asset Security Trends modal -->
<div class="modal fade" id="modal-asset-trends" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header bg-primary">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Asset Security Trends</h4>
      </div>

      <!-- Modal Body -->
      <div class="modal-body">
        <div id="asset-trends-buttons" style="text-align: center;">
          <button class="btn btn-xs" onclick="print_asset_trends_chart('week', 10);">last week</button>
          <button class="btn btn-xs" onclick="print_asset_trends_chart('month');">last month</button>
          <button class="btn btn-xs" onclick="print_asset_trends_chart('trimester');">last trimester</button>
          <button class="btn btn-xs" onclick="print_asset_trends_chart('year');">last year</button>
        </div>
        <div id="asset-trends">
          <!-- Content -->

          <canvas id="chart-asset-trends"/>
        </div>
        <button type="button" class="btn btn-xs btn-primary col-sm-12" data-dismiss="modal">Cancel</button><br/>
      </div>
    </div>
  </div>
</div>


<script>
  function toggle(source) {
    checkboxes = document.getElementsByName('finding');
    for(var i=0, n=checkboxes.length;i<n;i++) {
      checkboxes[i].checked = source.checked;
    }
  };

  var asset_trends_chart;

  function print_asset_trends_chart(period = "week", max_ticks = 20){
    if(asset_trends_chart){ asset_trends_chart.destroy(); }
    // update the findings stat pies
    asset_trends_chart_url = "/assets/api/v1/trends/{{asset.id}}?period_by="+period+"&max_ticks="+max_ticks;

    //data_labels_id = [];
    data_labels_date = [];
    data_datasets_total = [];
    data_datasets_new = [];
    data_datasets_info = [];
    data_datasets_low = [];
    data_datasets_medium = [];
    data_datasets_high = [];
    data_datasets_critical = [];
    data_datasets_grade = [];

    xhr = $.get(asset_trends_chart_url, function(resp) {
      for (i = 0; i < resp.length; i++){
        data_labels_date.push(resp[i]["date"]);
        data_datasets_total.push(resp[i]["total"]);
        data_datasets_new.push(resp[i]["new"]);
        data_datasets_info.push(resp[i]["info"]);
        data_datasets_low.push(resp[i]["low"]);
        data_datasets_medium.push(resp[i]["medium"]);
        data_datasets_high.push(resp[i]["high"]);
        data_datasets_critical.push(resp[i]["critical"]);
        data_datasets_grade.push(resp[i]["risk_grade"]);
      };

      asset_trends_chart_config = {
        type: 'bar',
        data: {
          datasets: [],
          borderWidth: 1
        },
        options: {
          responsive: true,
          maintainAspectRatio: true,
          legend: {
            display: true,
            position: 'top',
            //fullWidth: true,
            labels: {
              boxWidth: 20
            }
          },
          scales: {
            xAxes: [{
              stacked: true,
              gridLines: {
                display: false
              }
            }],
            yAxes:[{
              id: 'findings',
              position: 'left',
              scaleLabel: {
                display: true,
                labelString: '# findings found'
              },
              stacked: true,
              ticks: {
                beginAtZero: true,
                callback: function(value, index, values) {
                  if (Math.floor(value) === value) {
                    return value;
                  }
                }
              }
            }, {
              id: 'grades',
              position: 'right',
              scaleLabel: {
                display: true,
                labelString: 'Asset Security Grade'
              },
              gridLines : {
                  display : false
              },
              ticks: {
                min: 0,
                max: 6,
                stepSize: 1,
                callback: function(label, index, labels) {
                  switch (label) {
                    case 0:
                      return 'n/a';
                    case 1:
                      return 'F';
                    case 2:
                      return 'E';
                    case 3:
                      return 'D';
                    case 4:
                      return 'C';
                    case 5:
                      return 'B';
                    case 6:
                      return 'A';
                  }
                }
              }
            }]
          },
          tooltips: {
            mode: 'index',
            //yAlign: 'bottom',
            position: 'nearest',
            callbacks: {
              title: function(tooltipItems, data) {
                return data_labels_date[tooltipItems[0].index];
              }
            }
          }
        }
      }

      config = jQuery.extend(true, {}, asset_trends_chart_config);
      config["data"]["labels"] = data_labels_date;
      config["data"]["datasets"].push(
        {
          "type": "line",
          "label": "Grade",
          "data": data_datasets_grade,
          "fill": false, "lineTension": 0.1, "borderColor": "#2c3e50", "backgroundColor": "#FFFFFF",
          "yAxisID": "grades"
        },
        {
          "type": "line",
          "label": "Total",
          "data": data_datasets_total,
          "fill": false, "lineTension": 0, "borderColor": "#000000", "backgroundColor": "#FFFFFF",
          "hidden": true,
          "yAxisID": "findings"
        },
        {
          "type": "line",
          "label": "New",
          "data": data_datasets_new,
          "fill": false, "lineTension": 0.1, "borderColor": "#FF0000", "backgroundColor": "#FFFFFF",
          "hidden": true,
          "yAxisID": "findings"
        },
        {
          "label": "Info",
          "data": data_datasets_info,
          "fill": false, "lineTension": 0.1, "backgroundColor": "#3498db",
          "hidden": true,
          "yAxisID": "findings"
        },
        {
          "label": "Low",
          "data": data_datasets_low,
          "fill": false, "lineTension": 0.1, "backgroundColor": "#ffcb0d",
          "yAxisID": "findings"
        },
        {
          "label": "Medium",
          "data": data_datasets_medium,
          "fill": false, "lineTension": 0.1, "backgroundColor": "#f9a009",
          "yAxisID": "findings"
        },
        {
          "label": "High",
          "data": data_datasets_high,
          "fill": false, "lineTension": 0.1, "backgroundColor": "#df3d03",
          "yAxisID": "findings"
        },
        {
          "label": "Critical",
          "data": data_datasets_critical,
          "fill": false, "lineTension": 0.1, "backgroundColor": "#cc0500",
          "yAxisID": "findings"
        }
      );

      var canvas_asset_trends = document.getElementById("chart-asset-trends");
      var ctx = canvas_asset_trends.getContext("2d");
      asset_trends_chart = new Chart(canvas_asset_trends, config);

      // canvas_findings.onclick = function (evt) {
      //   var activePoints = findingsByScanDef_chart.getElementsAtEvent(evt);
      //   if (typeof activePoints != "undefined" && activePoints != null && activePoints.length > 0){
      //     var chartData = activePoints[0]['_chart'].config.data;
      //     var idx = activePoints[0]['_index'];
      //     var label = chartData.labels[idx];
      //     //var value = chartData.datasets[0].data[idx];
      //     window.location = "/scans/details/"+label;
      //   }
      // };
    });
  }; // End fo function print_asset_trends_chart()

  $(function() {
    // Delete selected findings
    $("a.btn-delete-selected").on('click', function(eventObject) {
      findings_to_delete = []
      $("input[name='finding']").each(function(cbx){
        if (this.checked) {
          findings_to_delete.push(this.value)
        }
      })

      if (findings_to_delete.length != 0){
        delete_url="{% url 'delete_findings_api' %}";
        var request = $.ajax({
          url: delete_url,
          method: "POST",
          headers: {"X-CSRFToken": "{{ csrf_token }}"},
          data: JSON.stringify(findings_to_delete),
          contentType: "application/json"
        });
        request.done(function(response){
          if (response.status == 'success'){location.reload()}
        });
      }
    });

    // Change the status on seleted findings
    $("a.btn-ack").on('click', function(eventObject) {
      findings_to_ack = [];
      $("input[name='finding']").each(function(cbx){
        if (this.checked) {
          findings_to_ack.push({'ack': this.value});
        }
      })

      if (findings_to_ack.length != 0){
        ack_url="{% url 'change_findings_status_api' %}";
        var request = $.ajax({
          url: ack_url,
          method: "POST",
          headers: {"X-CSRFToken": "{{ csrf_token }}"},
          data: JSON.stringify(findings_to_ack),
          contentType: "application/json"
        });
        request.done(function(response){
          if (response.status == 'success'){
            location.reload();
          }
        });
      }
    });

    // Compare findings
    $("a.btn-compare-selected").on('click', function (e) {
      findings_to_compare = [];
      $("input[name='finding']").each(function(cbx){
        if (this.checked) {
          findings_to_compare.push(this.value);
        }
      });
      if(findings_to_compare.length == 2){
        window.location.href ="/findings/compare?finding_a_id="+findings_to_compare[0]+"&finding_b_id="+findings_to_compare[1];
      }
    });

    // Delete tag
    $("i.delete-tag-btn").on('click', function(eventObject) {
      del_url="/assets/api/v1/details/{{asset.id}}/del_tag";
      tag_id = eventObject.currentTarget.getAttribute('tag-id');
      var request = $.ajax({
        url: del_url,
        method: "POST",
        headers: {"X-CSRFToken": "{{ csrf_token }}"},
        data: "tag_id="+tag_id,
        success: function(data, textStatus, xhr){
          location.reload();
        }
      });
    });

    // Autocomplete tags modal searchbar
    $("#input-search-tags").autocomplete({
      source: function(req, response) {
         $.ajax({
          url: "{% url 'get_asset_tags_api' %}",
          // url: "/assets/get_tags",
          dataType: "json",
          success: function( data ) {
            var re = $.ui.autocomplete.escapeRegex(req.term);
            var matcher = new RegExp(re, "i" ); //Start with
            response($.grep(data, function(item){return matcher.test(item.value || item.label || item);}) );
            }
          });
       },
      minLength: 2,
      appendTo: ".search-asset-tags-form",
      autoFocus: true
    });

    // Delete finding modal
    $("#modal-delete-finding").on('show.bs.modal', function (e) {
      finding_id = e.relatedTarget.getAttribute('finding-id');
      finding_title = e.relatedTarget.getAttribute('finding-title');
      $("div#delete-finding").attr('finding-id', finding_id);
      $("div#delete-finding").html("Finding: <b>"+finding_title+"</b><br/><br/>");
    });
    $("button.btn-delete-finding").on('click', function (e) {
      finding_id = $("div#delete-finding").attr('finding-id');
      delete_finding_url = "/findings/delete/"+finding_id;
      var request = $.ajax({
        url: delete_finding_url,
        method: "POST",
        headers: {"X-CSRFToken": "{{ csrf_token }}"},
        success: function(){
          location.reload();
        }
      });
    });

    // Fixing bootstrap tab issue
    $('#menu_tabs_ul > li > a').click(function(e) {
      $(this).removeClass('active');
    });

    print_asset_trends_chart('week');

  });
</script>


{% endblock %}
